const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const log4js = require('../utils/log4j')
const utils = require('../utils/utils')
const jwt = require('koa-jwt')
require('./database')

const index = require('../routes/index')
const userRouter = require('../routes/user.router')
const menuRouter = require('../routes/menu.router')

// error handler
onerror(app)

// middlewares
app.use(bodyparser({
  enableTypes:['json', 'form', 'text']
}))
app.use(json())
app.use(logger())
const pubPath = __dirname.replace('/app', '')
app.use(require('koa-static')(pubPath + '/public'))

app.use(views(pubPath + '/views', {
  extension: 'pug'
}))

// logger日志
app.use(async (ctx, next) => {
  log4js.info(`get params:${JSON.stringify(ctx.request.query)}`)
  log4js.info(`post params:${JSON.stringify(ctx.request.body)}`)
  await next().catch((err) => {
    if (err.status == '401') {
      ctx.status = 200
      log4js.error(`token认证失败！token: ${ctx.request.headers.token}`)
      ctx.body = utils.fail('token认证失败！', '', '401')
    } else {
      log4js.error(`服务器错误！${err}`)
      throw err
    }
  })
  // log.level = "debug" // 级别trace-debug-info-warn-error-fatal,越低级别打印越全
  // log.trace("some trace message")
  // log.debug("some debug message")
  // log.info("some info message")
})

app.use(async (ctx, next) => {
  let token = ctx.request.headers.token
  ctx.request.header = {'authorization': "Bearer " + token || ''}
  await next();
})

// jwt校验token是否失效, 要过滤的接口
app.use(jwt({secret: 'lls'}).unless({
  path: [/^\/users\/login/, /^\/users\/register/]
}))

// routes
app.use(index.routes(), index.allowedMethods())
app.use(userRouter.routes(), userRouter.allowedMethods())
app.use(menuRouter.routes(), menuRouter.allowedMethods())


// 全局错误监听处理
app.on('error', utils.errorHandler)
module.exports = app
